package com.reider.log4AS3.core
{
	import com.reider.log4AS3.event.ConfigXMLLoaderEvent;
	import com.reider.log4AS3.utils.LogUtils;
	import com.reider.log4AS3.utils.ObjectContainer;
	
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	
	[Event(name="configLoaded", type="com.reider.log4AS3.event.ConfigXMLLoaderEvent")]
	[Event(name="configError", type="com.reider.log4AS3.event.ConfigXMLLoaderEvent")]
	
	/**
	 * @private
	 */
	
	public class ConfigXMLLoader extends EventDispatcher
	{
		private var uLoader:URLLoader
		private var configFactory:XMLConfigFactory
		
		//--------------------------------------------------------------------------
	    //
	    //  Constructor
	    //
	    //--------------------------------------------------------------------------
		
		public function ConfigXMLLoader()
		{
			uLoader = new URLLoader()
			configFactory = new XMLConfigFactory()
			
			uLoader.addEventListener(Event.COMPLETE, onComplete)
			uLoader.addEventListener(IOErrorEvent.IO_ERROR, onError)
			uLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError)
		}
		
		//--------------------------------------------------------------------------
	    //
	    //  Public methods
	    //
	    //--------------------------------------------------------------------------
		
		public function loadURL(url:String):void
		{
			uLoader.load(new URLRequest(url))
		}
		
		//--------------------------------------------------------------------------
	    //
	    //  Callback methods
	    //
	    //--------------------------------------------------------------------------
		
		private function onComplete(event:Event):void
		{
			var dEvent:ConfigXMLLoaderEvent
			var loggerScopes:Array
			
			try{
				var xmlDat:XML = new XML(uLoader.data)
				loggerScopes = configFactory.getLoggerScopes( xmlDat )
				
			}catch(error:Error){
				dEvent = new ConfigXMLLoaderEvent(ConfigXMLLoaderEvent.CONFIG_ERROR)
				dEvent.errorMessage = "XML syntax error "+error.message
				dispatchEvent(dEvent)
				return
			}
			
			dEvent = new ConfigXMLLoaderEvent(ConfigXMLLoaderEvent.CONFIG_LOADED)
			dEvent.loggerScopes = loggerScopes
			dispatchEvent(dEvent)
		}
		
		private function onError(event:ErrorEvent):void
		{
			var dEvent:ConfigXMLLoaderEvent = new ConfigXMLLoaderEvent(ConfigXMLLoaderEvent.CONFIG_ERROR)
			dEvent.errorMessage = "XML load failed "+event.text
			dispatchEvent(dEvent)
		}
	}
}